<template>
	<canvas type="2d" canvas-id="canvasDom" @touchstart="touchstart" id="canvasDom" ref="canvasDom" :style="{width:canvasInfo.width+'px',height:canvasInfo.height+'px'}">
	</canvas>
</template>
<script>
	// #ifdef APP-PLUS
	const Main = plus.android.runtimeMainActivity();
	const Context = plus.android.importClass("android.content.Context");
	const WindowManagerImpl = plus.android.importClass("android.view.WindowManagerImpl")
	const WindowManager = plus.android.importClass("android.view.WindowManager")
	const Display = plus.android.importClass("android.view.Display")
	const getWindowManager = Main.getWindowManager().getDefaultDisplay();
	const refresh = getWindowManager.getRefreshRate(); //安卓刷新率
	console.log(refresh);
	// #endif
	export default {
		name: "CanvasDom",
		props:{
			countPlusFlag:{
				type:Boolean,
				default:()=>false
			},
			canvasInfo:{
				type:Object,
				default:()=>{
					return {
						width:0,
						height:0
					}
				}
			},
			plusCount:{
				type:String,
				default:()=>"1"
			},
			addType:{
				type:String,
				default:()=>"plus"
			},
			title:{
				type:String,
				default:()=>"功德"
			}
		},
		data() {
			return {
				renderArr:[], //渲染的数组
				renderArrTemp:[], //渲染的复制数组
				createImage:null,
				canvasNode:{},
				canvasDomInstance: null, //canvas画布
				canvasFrame:null,
				countPlusFlagTemp:{
					bool:false
				}
				// canvasInfo:{}
			}
		},
		methods: {
			touchstart(event){
				this.$emit("touchStart",event.touches[0])
			},
			createCurrentCanvas() {
				return new Promise((resolve,reject)=>{
					const query = uni.createSelectorQuery().in(this).select("#canvasDom")
					query.fields({
						node: true,
						size: true,
						rect:true,
						id:true,
						context:true
					}).exec((res)=>{
						const image = "/static/muyuIcon.png"
						// #ifdef MP-WEIXIN
						this.canvasNode = res[0].node
						const canvas = this.canvasNode
						this.canvasDomInstance = canvas.getContext('2d')
						// this.canvasDomInstance = uni.createCanvasContext('canvasDom')
						const ctx = this.canvasDomInstance
						const dpr = wx.getSystemInfoSync().pixelRatio
						canvas.width = this.canvasInfo["width"]  * dpr
						canvas.height = this.canvasInfo["height"] * dpr
						ctx.scale(dpr, dpr)
						this.createImage = this.canvasNode.createImage();
						this.createImage.src = image;
						this.createImage.onload = (res)=>{
							resolve(true)
						}
						// #endif
						// #ifdef APP-PLUS
						this.canvasDomInstance = uni.createCanvasContext('canvasDom')
						const ctx = this.canvasDomInstance
						uni.getImageInfo({
							src:image,
							fail:(err)=> {
								reject(false)
							},
							complete:(r)=> {
								this.createImage = {
									...r,
									src:image
								};
								resolve(true) 
							}
						})
						
						// #endif
						// #ifdef H5
						this.canvasDomInstance = uni.createCanvasContext('canvasDom')
						const ctx = this.canvasDomInstance
						this.createImage = new Image();
						this.createImage.src = image;
						this.createImage.onload = (res)=>{
							resolve(true)
						}
						// #endif
					})
				})
			},
			renderText(renderArr){
				this.renderArr = renderArr;
				this.renderArrTemp =	renderArr.map((item)=>{
					return {...item}
				})
				if(this.canvasDomInstance){
					// #ifdef MP-WEIXIN
					this.drawText(this.canvasDomInstance, 80, this.canvasInfo["width"] * 0.65,this.canvasNode)
					// #endif
					// #ifdef APP-PLUS
					this.canvasNode = {
						timer:null,
						cancelAnimationFrame:(timer)=>{
							clearTimeout(timer)
						},
						requestAnimationFrame:(callback)=>{
							this.canvasNode.timer ? this.canvasNode.cancelAnimationFrame(this.canvasNode.timer) : ""
							this.canvasNode.timer =	setTimeout(()=>{
								callback()
							},Math.round(1000/refresh))
							return this.canvasNode.timer
						}
					}
					this.drawText(this.canvasDomInstance, 80, this.canvasInfo["width"] * 0.65,this.canvasNode)
					// #endif
					// #ifdef H5
					this.drawText(this.canvasDomInstance, 80, this.canvasInfo.width * 0.65,window)
					// #endif
				}
			},
			drawImage(){
				let renderWidth = 0,renderHeight = 0,renderLeft = 0,renderTop = 0
				if(this.countPlusFlag){
					renderWidth = Math.floor(this.createImage.width*0.8);
					renderHeight = Math.floor(this.createImage.height*0.8);
					renderLeft = Math.floor((this.canvasInfo.width -	renderWidth)/2);
					renderTop = Math.floor((this.canvasInfo.height -	renderHeight)/2);
					// #ifdef MP-WEIXIN
					this.canvasDomInstance.drawImage(this.createImage,renderLeft,renderTop,renderWidth,renderHeight)
					// #endif
					// #ifdef APP-PLUS
					this.canvasDomInstance.drawImage(this.createImage.path,renderLeft,renderTop,renderWidth,renderHeight)
					// #endif
					// #ifdef H5
					this.canvasDomInstance.drawImage(this.createImage.src,renderLeft,renderTop,renderWidth,renderHeight)
					// #endif
				}else{
					renderWidth = Math.floor(this.createImage.width*0.9);
					renderHeight = Math.floor(this.createImage.height*0.9);
					renderLeft = Math.floor((this.canvasInfo.width -	renderWidth)/2)
					renderTop = Math.floor((this.canvasInfo.height -	renderHeight)/2)
					this.canvasDomInstance.clearRect(0, 0, this.canvasInfo.width, this.canvasInfo.height)
					// #ifdef MP-WEIXIN
					this.canvasDomInstance.drawImage(this.createImage,renderLeft,renderTop,renderWidth,renderHeight)
					// #endif
					// #ifdef APP-PLUS
					this.canvasDomInstance.drawImage(this.createImage.path,renderLeft,renderTop,renderWidth,renderHeight)
					// #endif
					// #ifdef H5
					this.canvasDomInstance.drawImage(this.createImage.src,renderLeft,renderTop,renderWidth,renderHeight)
					// #endif
				}
			},
			//rpx 转换为px
			rpxToPx(val, windowWidth) {
				const sysWidth = windowWidth || uni.getSystemInfoSync().windowWidth;
				let value = val * 1
				let returnVal = ((value / 750) * sysWidth).toFixed(2);
				return Math.round(returnVal)
			},
			drawText(ctx, baseTop, textLeft = 200, canvas) {
				const context = ctx;
				const basePercent = 0.008
				const fontSize = this.rpxToPx(42)
				let findItem = null;
				// let nowTime = performance.now();
				let digui = () => {
					if(this.canvasFrame){
						canvas.cancelAnimationFrame(this.canvasFrame)
					}
					findItem = null
					context.font = `${fontSize}px '微软雅黑'`;
					// 设置对齐方式
					context.textAlign = 'center';
					context.textBaseline = "top";
					context.clearRect(0, 0, this.canvasInfo.width, this.canvasInfo.height)
					this.drawImage()
					for(let i = 0;i<this.renderArr.length;i++){
						if(this.renderArr[i].render){ //透明的不用计算
							// 设置字体和字号
							context.fillStyle = `rgba(255,255,255,${this.renderArr[i].opacity})`;
							// 填充文字
							context.fillText(`${this.title}${this.addType == 'plus' ? '+':'-'}${this.plusCount}`, Math.round(this.renderArr[i].x), Math.floor(this.renderArr[i].y));
							if(this.renderArr[i].y > -100){
								this.renderArr[i].y = this.renderArr[i].y - 3
								// this.renderArr[i].y = ((this.renderArr[i].y - this.renderArrTemp[i].y*basePercent).toFixed(3)) * 1
							}
							if(this.renderArr[i].opacity > 0){
								this.renderArr[i].opacity = (this.renderArr[i].opacity - 0.02).toFixed(3)*1
							}else{
								this.renderArr[i].render = false
							}
						}
					}
					findItem = this.renderArr.find((item)=>item.render)
					if(!findItem){
						canvas.cancelAnimationFrame(this.canvasFrame)
						this.transparent()
						// #ifdef H5 || APP-PLUS
						context.draw()
						// #endif
						return false
					}
					// #ifdef H5 || APP-PLUS
					context.draw()
					// #endif
					// let renderTime = performance.now();
				return	this.canvasFrame = canvas.requestAnimationFrame(digui)
				}
				digui()
			},
			transparent(){
				this.$emit("transparent")
			},
		},
	 mounted() {
		 setTimeout(()=>{
			 this.createCurrentCanvas().then(()=>{
			 	this.drawImage()
			 	// #ifdef H5 || APP-PLUS
			 	this.canvasDomInstance.draw()
			 	// #endif
			 }).catch(()=>{});
		 },100)
			 
		}
	}
</script>

<style scoped lang="scss">
</style>
